package com.ruoyi.web.controller.gcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcCustomer;
import com.ruoyi.gcgl.domain.SjChance;
import com.ruoyi.gcgl.domain.SjProcessConfig;
import com.ruoyi.gcgl.service.IGcCustomerService;
import com.ruoyi.gcgl.service.IGcProjectService;
import com.ruoyi.gcgl.service.ISjChanceLinkmanService;
import com.ruoyi.gcgl.service.ISjChanceService;
import com.ruoyi.gcgl.service.ISjProcessConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;

/**
 * 商机跟踪Controller
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@Controller
@RequestMapping("/sj/chance")
public class SjChanceController extends BaseController
{
    private String prefix = "sj/chance";

    @Autowired
    private ISjChanceService sjChanceService;
    @Autowired
    private ISjChanceLinkmanService sjChanceLinkmanService;
    @Autowired
    private IGcCustomerService gcCustomerService;
    @Autowired
    private IGcProjectService gcProjectService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Autowired
    private ISjProcessConfigService sjProcessConfigService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleService roleService;
    
    final String processCode = "sjshangjilixiang";

    @RequiresPermissions("system:chance:view")
    @GetMapping()
    public String chance()
    {
        return prefix + "/chance";
    }

    /**
     * 查询商机跟踪列表
     */
    @RequiresPermissions("system:chance:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SjChance sjChance)
    {
        startPage();
        sjChance.setDeleteFlag(1);
        
      //角色数据权限 ==根据用户定义的数据权限查看项目数据
        List<SysRole> roles = getSysUser().getRoles();
        List<Long> roleIds = new ArrayList<Long>();
        for(SysRole obj:roles){
        	roleIds.add(obj.getRoleId());
        }
        
        int count = roleService.selectCountRoleDeptByRoleId(roleIds);
        if(count != 0){
        	//看部门
        	sjChance.setRoleIds(roleIds);
        }else{
        	//看个人
        	if(getSysUser().isShowRoleIds(roleIds)){
        		sjChance.setOwnerId(getUserId());
            }
        }
        //----
        
        List<SjChance> list = sjChanceService.selectSjChanceList(sjChance);
        return getDataTable(list);
    }

    /**
     * 导出商机跟踪列表
     */
    @RequiresPermissions("system:chance:export")
    @Log(title = "商机跟踪", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SjChance sjChance)
    {
        List<SjChance> list = sjChanceService.selectSjChanceList(sjChance);
        ExcelUtil<SjChance> util = new ExcelUtil<SjChance>(SjChance.class);
        return util.exportExcel(list, "商机跟踪数据");
    }

    /**
     * 新增商机跟踪
     */
    @GetMapping("/add")
    public String add(ModelMap mmap){
    	GcCustomer gcCustomer = new GcCustomer();
    	gcCustomer.setDeleteFlag(1);
    	List<GcCustomer> gcCustomerlis = gcCustomerService.selectGcCustomerList(gcCustomer);
    	mmap.put("clis", gcCustomerlis);
    	
    	mmap.put("owner", getLoginName());
    	mmap.put("ownerId", getUserId());
    	mmap.put("deptName", getSysUser().getDept().getDeptName());
    	mmap.put("deptId", getSysUser().getDept().getDeptId());
    	
    	//下一级审核人
//        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
//        mmap.put("approveid", configlis.get(0).getLevel1id());
//        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/add";
    }

    /**
     * 新增保存商机跟踪
     */
    @RequiresPermissions("system:chance:add")
    @Log(title = "商机跟踪", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SjChance sjChance){
    	sjChance.setOwner(getLoginName());
    	sjChance.setStatus(1);
    	sjChance.setDeleteFlag(1);
    	sjChance.setCreateAt(new Date());
    	sjChance.setCreateUser(getLoginName());
    	sjChance.setUpdateAt(new Date());
    	sjChance.setUpdateUser(getLoginName());
        return toAjax(sjChanceService.insertSjChance(sjChance));
    }

    /**
     * 修改商机跟踪
     */
    @RequiresPermissions("system:chance:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SjChance sjChance = sjChanceService.selectSjChanceById(id);
        mmap.put("sjChance", sjChance);
        
        GcCustomer gcCustomer = new GcCustomer();
    	gcCustomer.setDeleteFlag(1);
    	List<GcCustomer> gcCustomerlis = gcCustomerService.selectGcCustomerList(gcCustomer);
    	mmap.put("clis", gcCustomerlis);
    	
    	//下一级审核人
//        List<SjProcessConfig> configlis = returnUser(getSysUser().getDept().getDeptId());
//        mmap.put("approveid", configlis.get(0).getLevel1id());
//        mmap.put("approvename", configlis.get(0).getLevel1name());
        return prefix + "/edit";
    }

    /**
     * 修改保存商机跟踪
     */
    @RequiresPermissions("system:chance:edit")
    @Log(title = "商机跟踪", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SjChance sjChance){
    	sjChance.setOwner(getLoginName());
    	sjChance.setUpdateAt(new Date());
    	sjChance.setUpdateUser(getLoginName());
        return toAjax(sjChanceService.updateSjChance(sjChance));
    }

    /**
     * 删除商机跟踪
     */
    @RequiresPermissions("system:chance:remove")
    @Log(title = "商机跟踪", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(sjChanceService.deleteSjChanceByIds(ids));
    }
    
    //---------------------审批方法
    //申请人部门PID
    private List<SjProcessConfig> returnUser(Long deptId){
    	SysDept dept = deptService.selectDeptById(deptId);
    	SjProcessConfig sjProcessConfig = new SjProcessConfig();
        sjProcessConfig.setDeleteFlag(1);
        sjProcessConfig.setCode(processCode);
        sjProcessConfig.setDeptId(dept.getParentId());
        List<SjProcessConfig> configlis = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig);
		
        if(configlis==null || configlis.size()==0){
        	SjProcessConfig sjProcessConfig1 = new SjProcessConfig();
        	sjProcessConfig1.setDeleteFlag(1);
        	sjProcessConfig1.setCode("morenliucheng");
            List<SjProcessConfig> configlis1 = sjProcessConfigService.selectSjProcessConfigList(sjProcessConfig1);
            return configlis1;
        }
        return configlis;
    }
    
    /**
     * 修改保存项目立项
     */
    @Log(title = "商机立项", businessType = BusinessType.UPDATE)
    @PostMapping("/edit4check")
    @ResponseBody
    public AjaxResult edit4check(SjChance sjChance){
    	
    	GcCustomer gcCustomer = gcCustomerService.selectGcCustomerById(sjChance.getCustomerId());
    	if(gcCustomer!=null){
    		sjChance.setCustomerId(gcCustomer.getId());
    		sjChance.setCustomerName(gcCustomer.getName());
    	}
    	
    	sjChance.setUpdateAt(new Date());
    	sjChance.setUpdateUser(getLoginName());
        return toAjax(sjChanceService.updateSjChance4Check(sjChance));
    }
    
    /**
     * level1
     * @return
     */
    @GetMapping("/level1")
    public String level1(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	SjChance obj = sjChanceService.selectSjChanceById(Long.parseLong(p.getBusinessKey().toString()));
        	mmap.put("obj", obj);
        	
        	GcCustomer gcCustomer = new GcCustomer();
        	gcCustomer.setDeleteFlag(1);
        	List<GcCustomer> gcCustomerlis = gcCustomerService.selectGcCustomerList(gcCustomer);
        	mmap.put("clis", gcCustomerlis);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
            
            //下一级审核人
            List<SjProcessConfig> configlis = returnUser(Long.valueOf(obj.getDeptId().toString()));
            mmap.put("approveid", configlis.get(0).getLevel2id());
            mmap.put("approvename", configlis.get(0).getLevel2name());
        }
        
        return prefix + "/level1check";
    }
    
    /**
     * level2
     * @return
     */
    @GetMapping("/level2")
    public String level2(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	SjChance obj = sjChanceService.selectSjChanceById(Long.parseLong(p.getBusinessKey().toString()));
        	mmap.put("obj", obj);
        	
        	GcCustomer gcCustomer = new GcCustomer();
        	gcCustomer.setDeleteFlag(1);
        	List<GcCustomer> gcCustomerlis = gcCustomerService.selectGcCustomerList(gcCustomer);
        	mmap.put("clis", gcCustomerlis);
        	
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
        }
        
        return prefix + "/level2check";
    }
    
    /**
     * 修改单据
     * @param taskid
     * @param mmap
     * @return
     */
    @GetMapping("/modify")
    public String modify(String taskid, ModelMap mmap){
        Task t = taskService.createTaskQuery().taskId(taskid).singleResult();
        String processId = t.getProcessInstanceId();
        ProcessInstance p = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (p != null) {
        	SjChance obj = sjChanceService.selectSjChanceById(Long.parseLong(p.getBusinessKey().toString()));
            mmap.put("obj", obj);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mmap.put("taskid", taskid);
        }
        
        GcCustomer gcCustomer = new GcCustomer();
    	gcCustomer.setDeleteFlag(1);
    	List<GcCustomer> gcCustomerlis = gcCustomerService.selectGcCustomerList(gcCustomer);
    	mmap.put("clis", gcCustomerlis);
        
        return prefix + "/modifycheck";
    }
}